import pygame
import os
from gui.ui_manager import UIManager
from typing import List
from gui.animation_manager import AnimationManager
from gui.sound_manager import SoundManager
from gui.particle_system import ParticleSystem
from gui.screen_effects import ScreenEffects
from gui.transition_manager import TransitionManager, SlideTransition, FadeTransition
import math

class GameWindow:
    def __init__(self):
        pygame.init()
        self.width = 1080
        self.height = 600
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption("卡牌地下城")
        
        # 定义颜色
        self.BLACK = (0, 0, 0)
        self.WHITE = (255, 255, 255)
        self.BLUE = (0, 0, 255)
        
        # 获取资源目录路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        self.assets_dir = os.path.join(os.path.dirname(current_dir), 'assets')
        
        # 检查资源文件
        self.check_resources()
        
        # 加载资源
        self.load_resources()
        
        # 创建UI管理器
        self.ui_manager = UIManager(
            self.width, 
            self.height,
            normal_font_size=16,  # 从默认的20改为16
            small_font_size=14,   # 从默认的16改为14
            tiny_font_size=12     # 从默认的12改为10
        )
        
        # 添加动画效果
        self.animations = []
        
        # 加载更多视觉资源
        self.load_effects()
        
        # 添加按钮
        self.buttons = {
            'end_turn': pygame.Rect(
                self.width - 150,  # 右边距离
                self.height - 100,  # 底部距离
                120,  # 按钮宽度
                40   # 按钮高度
            )
        }
        
        # 创建动画管理器
        self.animation_manager = AnimationManager()
        
        # 创建音效管理器
        self.sound_manager = SoundManager()
        
        # 添加游戏状态
        self.game_states = {
            'victory': False,
            'defeat': False
        }
        
        # 添加粒子系统
        self.particle_system = ParticleSystem()
        
        # 添加屏幕效果
        self.screen_effects = ScreenEffects()
        
        # 创建转场效果管理器
        self.transition_manager = TransitionManager()
        
        self.game_state = None  # 添加这一行
        
    def check_resources(self):
        """检查必要的资源文件是否存在"""
        required_files = [
            os.path.join(self.assets_dir, 'backgrounds', 'title.png'),
            os.path.join(self.assets_dir, 'backgrounds', 'battle.png'),
            os.path.join(self.assets_dir, 'backgrounds', 'character_select.png'),
            os.path.join(self.assets_dir, 'cards', 'strike.png'),
            os.path.join(self.assets_dir, 'cards', 'defend.png'),
            os.path.join(self.assets_dir, 'characters', 'warrior.png'),
            os.path.join(self.assets_dir, 'characters', 'mage.png'),
        ]
        
        missing_files = []
        for file_path in required_files:
            if not os.path.exists(file_path):
                missing_files.append(file_path)
        
        if missing_files:
            print("缺少以下资源文件：")
            for file_path in missing_files:
                print(f"  - {file_path}")
            print("\n请先运行资源生成器：")
            print("python -m utils.resource_generator")
            raise FileNotFoundError("缺少必要的资源文件")
        
    def load_resources(self):
        """加载游戏资源"""
        try:
            base_path = os.path.dirname(os.path.dirname(__file__))
            assets_path = os.path.join(base_path, 'assets')
            print(f"Loading resources from: {assets_path}")
            
            # 加载背景图片
            self.backgrounds = {
                'title': pygame.image.load(os.path.join(assets_path, 'backgrounds', 'title.png')),
                'battle': pygame.image.load(os.path.join(assets_path, 'backgrounds', 'battle.png')),
                'character_select': pygame.image.load(os.path.join(assets_path, 'backgrounds', 'character_select.png')),
            }
            
            # 加载角色图片
            self.character_images = {
                'warrior': pygame.image.load(os.path.join(assets_path, 'characters', 'warrior.png')),
                'mage': pygame.image.load(os.path.join(assets_path, 'characters', 'mage.png')),
            }
            
            # 加载卡牌图片
            self.card_images = {}
            cards_path = os.path.join(assets_path, 'cards')
            card_name_mapping = {
                "打击": "strike.png",
                "防御": "defend.png",
                "连击": "double_strike.png",
                "格挡": "block.png",
                "蓄力": "power_up.png",
                "暴风": "double_storm.png"
            }
            
            for card_name, image_name in card_name_mapping.items():
                image_path = os.path.join(cards_path, image_name)
                if os.path.exists(image_path):
                    self.card_images[card_name] = pygame.image.load(image_path)
                    print(f"Loaded card image: {image_name}")
                else:
                    print(f"Warning: Card image not found: {image_path}")
            
            # 加载敌人图片
            self.enemy_images = {}
            enemies_path = os.path.join(assets_path, 'enemies')
            enemy_name_mapping = {
                "史莱姆": "史莱姆.png",
                "骷髅战士": "骷髅战士.png",
                "地精盗贼": "地精盗贼.png",
                "暗影法师": "暗影法师.png",
                "兽人战士": "兽人战士.png",
                "剧毒蜘蛛": "剧毒蜘蛛.png",
                "幽灵": "幽灵.png"
            }
            
            for enemy_name, image_name in enemy_name_mapping.items():
                image_path = os.path.join(enemies_path, image_name)
                if os.path.exists(image_path):
                    # 如果存在自定义图片，使用自定义图片
                    self.enemy_images[enemy_name] = pygame.image.load(image_path)
                    print(f"Loaded custom enemy image: {image_name}")
                else:
                    # 如果不存在，生成默��图片
                    print(f"Generating default image for: {enemy_name}")
                    if "史莱姆" in enemy_name:
                        color = (0, 255, 0, 180)  # 绿色半透明
                    elif "骷髅" in enemy_name:
                        color = (200, 200, 200, 180)  # 灰白色
                    elif "地精" in enemy_name:
                        color = (0, 180, 0, 180)  # 深绿色
                    elif "法师" in enemy_name:
                        color = (100, 0, 200, 180)  # 紫色
                    elif "兽人" in enemy_name:
                        color = (150, 100, 50, 180)  # 棕色
                    elif "蜘蛛" in enemy_name:
                        color = (100, 0, 0, 180)  # 深红色
                    elif "幽灵" in enemy_name:
                        color = (200, 200, 255, 180)  # 淡蓝色
                    else:
                        color = (150, 150, 150, 180)  # 默认灰色
                    
                    self.enemy_images[enemy_name] = self.generate_enemy_image(120, 120, color, enemy_name)
            
            # 打印已加载的资源信息
            print("\nLoaded enemy images:")
            for name, image in self.enemy_images.items():
                source = "custom" if os.path.exists(os.path.join(enemies_path, enemy_name_mapping[name])) else "generated"
                print(f"- {name}: {source}")
            
        except Exception as e:
            print(f"Error loading resources: {e}")
            import traceback
            traceback.print_exc()
        
    def generate_enemy_image(self, width, height, color, enemy_type):
        """生成敌人图像"""
        surface = pygame.Surface((width, height), pygame.SRCALPHA)
        
        if "史莱姆" in enemy_type:
            # 绘制史莱姆
            pygame.draw.ellipse(surface, color, (20, height//3, width-40, height//2))
            pygame.draw.ellipse(surface, (255, 255, 255), (width//3, height//3, 20, 20))
        elif "骷髅" in enemy_type:
            # 绘制骷髅
            pygame.draw.circle(surface, color, (width//2, height//3), width//4)
            pygame.draw.rect(surface, color, (width//3, height//2, width//3, height//3))
        
        return surface
        
    def load_effects(self):
        """加载特效资源"""
        self.effects = {
            'card_glow': self.generate_glow_effect((255, 255, 0), 120, 180),
            'attack_flash': self.generate_flash_effect((255, 0, 0)),
        }
        
    def generate_glow_effect(self, color, width, height):
        """生成发光效果"""
        surface = pygame.Surface((width, height), pygame.SRCALPHA)
        for i in range(10):
            alpha = 255 - (i * 25)
            pygame.draw.rect(surface, (*color, alpha),
                            (i, i, width - 2*i, height - 2*i), 2)
        return surface
        
    def generate_flash_effect(self, color):
        """生成闪光效果"""
        surface = pygame.Surface((100, 100), pygame.SRCALPHA)
        pygame.draw.circle(surface, (*color, 180), (50, 50), 50)
        return surface
        
    def draw_title_screen(self):
        """绘制标题画面"""
        self.screen.blit(self.backgrounds['title'], (0, 0))
        # 绘制开始按钮等UI元素
        
    def draw_battle_screen(self, game_state, hovered_card=None):
        """绘制战斗画面"""
        self.game_state = game_state
        
        # 获取屏幕震动偏移量
        shake_offset = self.screen_effects.update(1/60)
        
        # 创建临时surface
        temp_surface = pygame.Surface((self.width, self.height))
        temp_surface.blit(self.backgrounds['battle'], (0, 0))
        
        # 1. 绘制顶部状态栏（玩家信息）
        self.draw_player_status_bar(temp_surface, game_state.player)
        
        # 2. 绘制敌人信息和战场区域
        self.draw_battle_area(temp_surface, game_state)
        
        # 3. 绘制底部卡牌区域
        self.draw_card_area(temp_surface, game_state.player, hovered_card)
        
        # 4. 绘制战斗日志
        self.draw_battle_log(temp_surface)
        
        # 5. 绘制UI元素
        self.ui_manager.update()
        self.ui_manager.draw(temp_surface)
        
        # 6. 绘制特效
        self.particle_system.update(1/60)
        self.particle_system.draw(temp_surface)
        
        # 应用震动效果并绘制屏幕
        self.screen.blit(temp_surface, shake_offset)
        
        # 如果战斗结束，显示战利品界面
        if game_state.current_room["completed"] and game_state.battle_rewards:
            self.draw_rewards_screen(game_state.battle_rewards)
            
            # 如果已经选择了卡牌，显示选择效果
            if game_state.battle_rewards.get("selected_card"):
                self.handle_card_select(
                    game_state.battle_rewards["selected_card"],
                    (self.width//2, self.height//2)
                )
        
        # 绘制转场效果
        self.transition_manager.update(1/60)
        self.transition_manager.draw(self.screen)

    def draw_player_status_bar(self, surface, player):
        """绘制玩家状态栏"""
        # 状态栏背景
        status_bar = pygame.Surface((self.width, 60), pygame.SRCALPHA)  # 减小高度
        status_bar.fill((0, 0, 0, 180))
        surface.blit(status_bar, (0, 0))
        
        # 生命值条
        hp_percent = player.stats["current_hp"] / player.stats["max_hp"]
        hp_bar_width = 180  # 减小宽度
        hp_bar_height = 15  # 减小高度
        pygame.draw.rect(surface, (80, 0, 0), (20, 15, hp_bar_width, hp_bar_height))
        pygame.draw.rect(surface, (200, 0, 0), (20, 15, hp_bar_width * hp_percent, hp_bar_height))
        
        # 生命值文本
        hp_text = self.ui_manager.normal_font.render(
            f"生命: {player.stats['current_hp']}/{player.stats['max_hp']}", True, self.WHITE)
        surface.blit(hp_text, (20, 35))
        
        # 法力值文本
        mana_text = self.ui_manager.normal_font.render(
            f"法力: {player.stats['current_mana']}/{player.stats['max_mana']}", True, (50, 50, 255))
        surface.blit(mana_text, (200, 35))
        
        # 卡牌数量文本
        deck_text = self.ui_manager.small_font.render(
            f"牌堆: {len(player.deck)} 手牌: {len(player.hand)} 弃牌: {len(player.discard_pile)}",
            True, (200, 200, 200))
        surface.blit(deck_text, (350, 20))
        
        # 金币显示
        gold_text = self.ui_manager.normal_font.render(
            f"金币: {player.stats['gold']}", True, (255, 215, 0))
        surface.blit(gold_text, (350, 35))
        
        # 添加楼层显示
        if self.game_state:
            floor_text = self.ui_manager.normal_font.render(
                f"第 {self.game_state.current_floor} 层 - 房间 {self.game_state.dungeon.current_room + 1}",
                True, (255, 215, 0))
            surface.blit(floor_text, (self.width - 200, 45))

    def draw_battle_area(self, surface, game_state):
        """绘制战斗区域"""
        if game_state.current_room["type"] != "combat":
            print("当前房间不是战斗房间")
            return
        
        enemy = game_state.current_room["content"]["enemy"]
        enemy_name = enemy.get_name()
        
        # 调整敌人区域的位置（向下移动）
        enemy_area = pygame.Surface((400, 250), pygame.SRCALPHA)
        enemy_area.fill((0, 0, 0, 120))
        enemy_x = self.width//2 - 200
        enemy_y = 150  # 从100改为150
        surface.blit(enemy_area, (enemy_x, enemy_y))
        
        try:
            # 敌人图像
            if enemy_name in self.enemy_images:
                enemy_image = pygame.transform.scale(self.enemy_images[enemy_name], (100, 100))  # 稍微缩小图片
                image_x = enemy_x + 150  # 居中放置
                image_y = enemy_y + 120  # 调整垂直��置
                surface.blit(enemy_image, (image_x, image_y))
        except Exception as e:
            print(f"绘制敌人图像时出错: {e}")
        
        # 敌人名称和等级（调整位置）
        name_text = f"{enemy.get_name()} Lv.{enemy.level}"
        name_surface = self.ui_manager.normal_font.render(name_text, True, (255, 255, 255))
        surface.blit(name_surface, (enemy_x + 200 - name_surface.get_width()//2, enemy_y + 30))
        
        # 敌人生命值条（调整位置和大小）
        hp_text = f"生命: {enemy.current_hp}/{enemy.max_hp}"
        hp_surface = self.ui_manager.normal_font.render(hp_text, True, (255, 255, 255))
        hp_percent = enemy.current_hp / enemy.max_hp
        hp_bar_width = 250  # 稍微减小血条宽度
        hp_bar_height = 15  # 减小血条高度
        
        # 血条背景
        pygame.draw.rect(surface, (80, 0, 0), 
                        (enemy_x + 75, enemy_y + 70, hp_bar_width, hp_bar_height))
        # 当前血量
        pygame.draw.rect(surface, (200, 0, 0),
                        (enemy_x + 75, enemy_y + 70, 
                         int(hp_bar_width * hp_percent), hp_bar_height))
        # 血量文字
        surface.blit(hp_surface, (enemy_x + 200 - hp_surface.get_width()//2, enemy_y + 90))
        
        # 敌人意图显示��调整位置）
        if enemy.next_action:
            # 意图背景
            intent_bg = pygame.Surface((150, 30), pygame.SRCALPHA)
            intent_bg.fill((0, 0, 0, 150))
            intent_x = enemy_x + 125
            intent_y = enemy_y - 10  # 调整意图显示位置
            surface.blit(intent_bg, (intent_x, intent_y))
            
            # 意图图标
            action_type = enemy.next_action["type"]
            icon_color = (255, 0, 0) if action_type == "attack" else (0, 255, 255)
            pygame.draw.circle(surface, icon_color, (intent_x + 15, intent_y + 15), 8)
            
            # 意图文本
            intent_text = f"{enemy.next_action['name']}"
            if 'damage' in enemy.next_action:
                intent_text += f" ({enemy.next_action['damage']})"
            
            text_surface = self.ui_manager.small_font.render(intent_text, True, (255, 255, 255))
            surface.blit(text_surface, (intent_x + 30, intent_y + 8))
        
        # 敌人状态效果（如果有）
        if hasattr(enemy, 'status_effects') and enemy.status_effects:
            status_x = enemy_x + 50
            for i, (status, value) in enumerate(enemy.status_effects.items()):
                status_bg = pygame.Surface((30, 30), pygame.SRCALPHA)
                status_bg.fill((0, 0, 0, 150))
                surface.blit(status_bg, (status_x + i*35, enemy_y + 200))
                
                status_text = self.ui_manager.tiny_font.render(str(value), True, (255, 255, 255))
                surface.blit(status_text, (status_x + i*35 + 15 - status_text.get_width()//2, 
                                         enemy_y + 215))

    def draw_card_area(self, surface, player, hovered_card=None):
        """绘制卡牌区域"""
        # 卡牌区域背景
        card_area = pygame.Surface((self.width, 220), pygame.SRCALPHA)
        card_area.fill((0, 0, 0, 150))
        surface.blit(card_area, (0, self.height - 220))
        
        # 绘制手牌
        self.draw_hand_cards(surface, player.hand, hovered_card)
        
        # 绘制结束回合按钮
        self.draw_end_turn_button(surface)

    def draw_hand_cards(self, surface, hand, hovered_card=None):
        """绘制手牌"""
        if not hand:
            return
        
        card_width = 120
        card_spacing = 20
        total_width = len(hand) * (card_width + card_spacing) - card_spacing
        start_x = (self.width - total_width) // 2
        
        for i, card in enumerate(hand):
            x = start_x + i * (card_width + card_spacing)
            y = self.height - 200
            is_hovered = (card == hovered_card)
            self.draw_card(surface, card, x, y, highlighted=is_hovered)

    def draw_card(self, surface, card, x, y, highlighted=False):
        """绘制卡牌"""
        card_width = 120
        card_height = 180
        
        # 创建卡牌背景
        card_surface = pygame.Surface((card_width, card_height), pygame.SRCALPHA)
        
        # 根据卡牌类型设置默认的背景色和边框色
        if card.card_type == "attack":
            bg_color = (200, 50, 50, 200)
            border_color = (255, 100, 100)
        elif card.card_type == "defense":
            bg_color = (50, 50, 200, 200)
            border_color = (100, 100, 255)
        else:  # skill
            bg_color = (50, 200, 50, 200)
            border_color = (100, 255, 100)
        
        # 创建卡牌名称到文件名的映射
        card_name_mapping = {
            "打击": "strike",
            "防御": "defend",
            "连击": "double_strike",
            "格挡": "block",
            "蓄力": "power_up",
            "暴风": "double_storm"
        }
        
        # 获取对应的英文文件名
        file_name = card_name_mapping.get(card.name, card.name.lower())
        
        # 尝试取或加载卡牌图片
        if file_name not in self.card_images:
            try:
                image_path = os.path.join(self.assets_dir, 'cards', f'{file_name}.png')
                if os.path.exists(image_path):
                    self.card_images[file_name] = pygame.image.load(image_path)
            except Exception as e:
                print(f"无法加载卡牌图片 {file_name}: {e}")
        
        # 使用图或绘制默认背景
        if file_name in self.card_images:
            card_image = pygame.transform.scale(self.card_images[file_name], (card_width, card_height))
            card_surface.blit(card_image, (0, 0))
        else:
            # 使用默认背景色
            pygame.draw.rect(card_surface, bg_color, (0, 0, card_width, card_height), border_radius=10)
        
        # 绘制边框
        pygame.draw.rect(card_surface, border_color, (0, 0, card_width, card_height), 2, border_radius=10)
        
        # 如果是高亮状态，添加发光效果
        if highlighted:
            glow_surface = pygame.Surface((card_width + 10, card_height + 10), pygame.SRCALPHA)
            pygame.draw.rect(glow_surface, (255, 255, 0, 100), 
                            (0, 0, card_width + 10, card_height + 10), border_radius=12)
            surface.blit(glow_surface, (x - 5, y - 5))
        
        # 绘制卡牌费用（左上角圆形）
        cost_circle_pos = (20, 20)
        pygame.draw.circle(card_surface, (50, 50, 200), cost_circle_pos, 15)
        pygame.draw.circle(card_surface, (100, 100, 255), cost_circle_pos, 15, 2)
        
        # 绘制费用数字
        cost_text = self.ui_manager.normal_font.render(str(card.cost), True, (255, 255, 255))
        cost_rect = cost_text.get_rect(center=cost_circle_pos)
        card_surface.blit(cost_text, cost_rect)
        
        # 绘制卡牌名称
        name_text = self.ui_manager.small_font.render(card.name, True, (255, 255, 255))
        name_rect = name_text.get_rect(center=(card_width//2, 30))
        card_surface.blit(name_text, name_rect)
        
        # 绘制卡牌描述（自动换行）
        desc_lines = self.wrap_text(card.description, card_width - 20)
        for i, line in enumerate(desc_lines):
            desc_text = self.ui_manager.small_font.render(line, True, (255, 255, 255))
            desc_rect = desc_text.get_rect(center=(card_width//2, 130 + i * 20))
            card_surface.blit(desc_text, desc_rect)
        
        # 将卡牌绘制到主surface上
        surface.blit(card_surface, (x, y))

    def wrap_text(self, text: str, width: int) -> List[str]:
        """将文本按指定宽度换行"""
        words = text.split(' ')
        lines = []
        current_line = []
        current_width = 0
        
        for word in words:
            word_surface = self.ui_manager.small_font.render(word + ' ', True, (0, 0, 0))
            word_width = word_surface.get_width()
            
            if current_width + word_width > width:
                lines.append(' '.join(current_line))
                current_line = [word]
                current_width = word_width
            else:
                current_line.append(word)
                current_width += word_width
        
        if current_line:
            lines.append(' '.join(current_line))
        
        return lines 

    def draw_victory_screen(self):
        """绘制胜利画面"""
        overlay = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))
        self.screen.blit(overlay, (0, 0))
        
        victory_text = self.ui_manager.title_font.render("胜利！", True, (255, 255, 0))
        text_rect = victory_text.get_rect(center=(self.width//2, self.height//2))
        self.screen.blit(victory_text, text_rect)

    def draw_defeat_screen(self):
        """绘制失败画面"""
        overlay = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))
        self.screen.blit(overlay, (0, 0))
        
        defeat_text = self.ui_manager.title_font.render("失败...", True, (255, 0, 0))
        text_rect = defeat_text.get_rect(center=(self.width//2, self.height//2))
        self.screen.blit(defeat_text, text_rect) 

    def handle_card_play(self, card, target_pos):
        """处理卡牌使用效果"""
        # 播放卡牌使用音效
        self.sound_manager.play_sound('card_play')
        
        # 添加卡牌飞行动画
        self.animation_manager.add_card_animation(
            start_pos=(self.width//2, self.height - 100),
            end_pos=target_pos
        )
        
        # 添加伤害数字动画
        if hasattr(card, 'damage'):
            self.particle_system.create_damage_numbers(
                target_pos[0], target_pos[1],
                str(card.damage),
                (255, 0, 0)
            )
        
        # 添加使用提示
        self.ui_manager.add_message(
            f"使用了 {card.name}",
            color=(255, 255, 255)
        )

    def get_card_position(self, card, game_state):
        """获取卡牌在手牌中的位置"""
        card_width = 100
        card_spacing = 15
        card_height = 150
        
        if card in game_state.player.hand:
            index = game_state.player.hand.index(card)
            start_x = (self.width - (len(game_state.player.hand) * (card_width + card_spacing))) // 2
            x = start_x + index * (card_width + card_spacing)
            y = self.height - card_height - 15
            return (x, y)
        return (0, 0) 

    def start_battle_transition(self):
        """开始战斗转场"""
        self.transition_manager.start_transition(
            SlideTransition(0.5, "right", 
                           on_complete=lambda: self.sound_manager.play_music('battle'))
        )

    def end_battle_transition(self):
        """结束战斗转场"""
        self.transition_manager.start_transition(
            FadeTransition(1.0, 
                          on_complete=lambda: self.sound_manager.play_sound('victory'))
        ) 

    def draw_character_select(self):
        """绘制角色选择画面"""
        # 绘制背景
        self.screen.blit(self.backgrounds['character_select'], (0, 0))
        
        # 绘制标题
        title_text = self.ui_manager.title_font.render("选择你的角色", True, self.WHITE)
        title_rect = title_text.get_rect(center=(self.width//2, 80))
        self.screen.blit(title_text, title_rect)
        
        # 设置角色卡片的大小位置
        card_width = 200
        card_height = 300
        spacing = 100
        
        # 战士卡片位置
        warrior_x = self.width//3 - card_width//2
        warrior_y = self.height//2 - card_height//2
        
        # 法师卡片位置
        mage_x = 2*self.width//3 - card_width//2
        mage_y = self.height//2 - card_height//2
        
        # 绘制角色卡片背景（半透明）
        for pos in [(warrior_x, warrior_y), (mage_x, mage_y)]:
            card_surface = pygame.Surface((card_width, card_height), pygame.SRCALPHA)
            card_surface.fill((0, 0, 0, 150))
            self.screen.blit(card_surface, pos)
        
        # 绘制战士
        warrior_image = pygame.transform.scale(self.character_images['warrior'], (160, 160))
        self.screen.blit(warrior_image, (warrior_x + 20, warrior_y + 20))
        
        warrior_text = self.ui_manager.normal_font.render("战士", True, self.WHITE)
        self.screen.blit(warrior_text, (warrior_x + card_width//2 - warrior_text.get_width()//2, 
                                      warrior_y + 200))
        
        warrior_desc = [
            "擅长近战",
            "基础生命值高",
            "起始防御卡组"
        ]
        
        for i, line in enumerate(warrior_desc):
            desc_text = self.ui_manager.small_font.render(line, True, (200, 200, 200))
            self.screen.blit(desc_text, (warrior_x + 20, warrior_y + 230 + i*25))
        
        # 绘制法师
        mage_image = pygame.transform.scale(self.character_images['mage'], (160, 160))
        self.screen.blit(mage_image, (mage_x + 20, mage_y + 20))
        
        mage_text = self.ui_manager.normal_font.render("法师", True, self.WHITE)
        self.screen.blit(mage_text, (mage_x + card_width//2 - mage_text.get_width()//2, 
                                    mage_y + 200))
        
        mage_desc = [
            "擅长法术",
            "基础法力值高",
            "起始攻击卡组"
        ]
        
        for i, line in enumerate(mage_desc):
            desc_text = self.ui_manager.small_font.render(line, True, (200, 200, 200))
            self.screen.blit(desc_text, (mage_x + 20, mage_y + 230 + i*25))
        
        # 绘制选择提示
        hint_text = self.ui_manager.normal_font.render("点击选择角色", True, (255, 255, 0))
        hint_rect = hint_text.get_rect(center=(self.width//2, self.height - 50))
        self.screen.blit(hint_text, hint_rect) 

    def draw_end_turn_button(self, surface):
        """绘制回合结束按钮"""
        # 绘制按钮背景
        pygame.draw.rect(surface, (50, 150, 50), self.buttons['end_turn'], border_radius=5)
        
        # 按钮文本
        text = self.ui_manager.normal_font.render("结束回合", True, self.WHITE)
        text_rect = text.get_rect(center=self.buttons['end_turn'].center)
        surface.blit(text, text_rect)
        
        # 添加按钮边框
        pygame.draw.rect(surface, (30, 100, 30), self.buttons['end_turn'], 2, border_radius=5) 

    def draw_battle_log(self, surface):
        """绘制战斗日志"""
        # 创建日志区域即使没有消息也显示）
        log_area = pygame.Surface((250, 200), pygame.SRCALPHA)
        log_area.fill((0, 0, 0, 150))
        
        # 在右上角显示战斗日志
        log_x = self.width - 270
        log_y = 100
        surface.blit(log_area, (log_x, log_y))
        
        # 添加标题
        title = self.ui_manager.normal_font.render("战斗日志", True, (255, 255, 0))
        surface.blit(title, (log_x + 10, log_y + 5))
        
        # 显示最近的战斗记录
        if self.ui_manager.messages:
            for i, message in enumerate(self.ui_manager.messages[-5:]):
                text = self.ui_manager.small_font.render(message['text'], True, message['color'])
                surface.blit(text, (log_x + 10, log_y + 35 + i * 25))
        else:
            # 如果没有消息，显示默认文本
            text = self.ui_manager.small_font.render("等待行动...", True, (200, 200, 200))
            surface.blit(text, (log_x + 10, log_y + 35))

    def handle_card_hover(self, pos):
        """处理卡牌悬停效果"""
        if not self.game_state:
            return None
        
        for card in self.game_state.player.hand:
            card_pos = self.get_card_position(card, self.game_state)
            card_rect = pygame.Rect(card_pos[0], card_pos[1], 120, 160)
            
            if card_rect.collidepoint(pos):
                # 显示卡牌详细信息
                tooltip_text = (f"{card.name}\n"
                              f"费用: {card.cost}\n"
                              f"类型: {card.card_type}\n"
                              f"效果: {card.description}")
                self.ui_manager.show_tooltip(tooltip_text, pos)
                return card
        
        self.ui_manager.tooltips.clear()
        return None 

    def draw_rewards_screen(self, rewards):
        """绘制战利品界面"""
        # 创建半透明背景
        overlay = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        self.screen.blit(overlay, (0, 0))
        
        # 绘制标题
        title = self.ui_manager.title_font.render("战斗胜利！", True, (255, 215, 0))
        title_rect = title.get_rect(center=(self.width//2, 100))
        self.screen.blit(title, title_rect)
        
        # 绘制金币奖励
        gold_text = self.ui_manager.normal_font.render(f"获得 {rewards['gold']} 金币", True, (255, 215, 0))
        gold_rect = gold_text.get_rect(center=(self.width//2, 160))
        self.screen.blit(gold_text, gold_rect)
        
        # 绘制卡牌选择提示
        if not rewards.get("selected_card"):
            card_text = self.ui_manager.normal_font.render("选择一张卡牌加入牌组:", True, (255, 255, 255))
            self.screen.blit(card_text, (self.width//2 - 200, 220))
            
            # 绘制三张奖励卡牌
            card_spacing = 220
            start_x = self.width//2 - card_spacing
            
            for i, card in enumerate(rewards["cards"]):
                x = start_x + i * card_spacing
                self.draw_card(self.screen, card, x - 60, 260)

    def handle_card_select(self, card, pos):
        """处理卡牌选择的动画效果"""
        # 播放选择音效
        self.sound_manager.play_sound('card_select')
        
        # 创建卡牌选中特效
        self.particle_system.create_card_trail(
            pos[0], pos[1],
            0, -100,  # 向上飘动
            (255, 215, 0),  # 金色
            30
        )
        
        # 添加闪光效果
        self.screen_effects.add_flash(0.3, (255, 215, 0)) 